const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const authenticateJWT = require("./middlewares/authenticateJWT");
const cors = require('cors');



const common = require("./routes/common");
const indexRouter = require("./routes/index");

const app = express();

app.use(logger("dev"));
app.use(express.json()); // 解析json格式的请求体
app.use(express.urlencoded({ extended: false })); // 解析urlencoded格式的请求体
// app.use(cookieParser());
app.use(cors());
// 静态资源
app.use("/images", express.static(path.join(__dirname, "uploads", "images"), { maxAge: "7d" }));
app.use("/video", express.static(path.join(__dirname, "uploads", "videos"), { maxAge: "7d" }));
app.use("/documents", express.static(path.join(__dirname, "uploads", "documents")));
// 公共路由
app.use("/", common);
// JWT验证
app.use(authenticateJWT);
// 路由
app.use("/", indexRouter);
// 捕获404并转发到错误处理程序
app.use(function (req, res, next) {
  console.log("404");
  res.status(404).send(404);
});

// 错误处理程序
app.use(function (err, req, res, next) {
  console.error("异常msg：", err.message);
  console.error("错误name:", err.name);
  console.error(err);

  // 文件错误
  if (err.name === "MulterError" && err.code === "LIMIT_FILE_SIZE") {
    return res.json({ code: -1, message: "文件大小超过限制" });
  }
  // 设置本地变量，仅在开发环境中提供错误信息
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  res.status(500).json({ code: 500, message: "服务器错误" });
});

app.listen(3000, () => {
  console.log(`Server running at Port:${3000}`);
});
